<template>
	<div v-if="formState !== 'hidden'">
		<div class="container">
			<div class="container_title">基础信息</div>
			<div class="container_content">
				<FormItems
					ref="form"
					v-model="infoData"
					:form="formList"
					labelWidth="140px"
					:column="3"
					:state="formState"></FormItems>
				<!-- state="readonly" -->
			</div>
		</div>
	</div>
</template>
<script>
	import * as regs from '@/utils/validator.js';
	import FormItems from '@/views/finance/manage/formItems/index.vue';
	import * as apis from '@/api/app.js';
	import {
		UserList,
		SupplierDetails,
		clientDetails,
		DriverDetails,
	} from '@/api/finance/reimburs/add/api.js';
	export default {
		name: 'info',
		props: {
			value: {
				default: {},
			},
			state: {
				default: 'write',
			},
			formStatus: {
				required: false,
			},
		},
		components: { FormItems },
		data() {
			return {
				deptList: {
					company: [], //公司
					department: [], // 组织
				},
				// formList: [],
				dicts: {
					// 收款人类型
					payeeTypeList: [
						{
							label: '员工',
							value: '1',
						},
						{
							label: '司机',
							value: '2',
						},
						{
							label: '供应商',
							value: '3',
						},
					],
					contractTypeList: [
						{
							label: '短租',
							value: '1',
						},
						{
							label: '渠道',
							value: '2',
						},
						{
							label: '自营',
							value: '3',
						},
						{
							label: '代收代付',
							value: '4',
						},
					],
					needpayType: [
						{
							label: '是',
							value: '1',
						},
						{
							label: '否',
							value: '2',
						},
					],
					BusinessType: [],
					paymentAccount: [],
				},
				payeeUserId: {
					selectList: [],
					prototype: {
						loading: false,
					},
				},
				paymentAccountLoading: false,
			};
		},

		computed: {
			infoData: {
				get() {
					return this.useVModel.call(this);
				},
				set(value) {
					this.$emit('input', value);
				},
			},
			formState: {
				get() {
					let state = 'write';
					if (Reflect.has(this, 'formStatus')) {
						switch (this?.formStatus?.toString()) {
							case '0':
								state = 'write';
								break;
							case '1':
								state = 'disabled';
								break;
							case '2':
								state = 'hidden';
								break;
							default:
								state = this.state;
								break;
						}
					}
					return state;
				},
			},
			formList() {
				return [
					// {
					//     label: "所属公司",
					//     type: "select_dialog",
					//     propLabel: "companyName",
					//     prop: "companyId",
					//     selectDialogParams: {
					//         type: "company",
					//         title: "请选择公司",
					//     },
					//     rules: [
					//         {
					//             required: true,
					//             message: "请选择公司",
					//             trigger: "change",
					//         },
					//     ],
					//     rulesProp: "companyId",
					//     cb: (row, res) => {
					//         this.$set(row, "companyName", res.companyName);
					//         this.$set(row, "companyId", res.companyId);
					//         this.infoData?.businessTypeVos?.map((item) => {
					//             this.$emit(ele, "companyName", res.companyName);
					//             this.$set(ele, "companyId", res.companyId);
					//         });
					//     },
					// },
					{
						label: '所属公司',
						type: 'select',
						selectList: this.deptList?.company ?? [],
						prop: 'companyId',
						selectValue: 'deptId',
						selectLabel: 'deptName',
						rules: [
							{
								required: true,
								message: '请选择公司',
								trigger: 'change',
							},
						],

						event: {
							type: 'change',
							cb: row => {
								let item = this.deptList?.company.find(
									e => e.deptId == row.companyId,
								);
								this.payeeUserId.selectList = [];
								row.payeeType = undefined;
								row.payeeUserId = undefined;
								row.payeeUserName = undefined;
								row.paymentCardId = undefined;
								row.paymentAccount = undefined;
								if (!item) return;
								row.companyName = item.deptName;
								this.infoData.businessTypeVos = [];
								// this.infoData?.businessTypeVos?.forEach((child) => {
								//     child?.businessInfoVos?.forEach((e) => {
								//         e.companyId = item.deptId;
								//         e.companyName = item.deptName;
								//     });
								// });
								this.$emitter.emit('reimburs_init');
							},
						},
					},
					{
						label: '收款人类型',
						type: 'radioGroup',
						prop: 'payeeType',
						radioGroupList: this.dicts.payeeTypeList ?? [],
						rules: [
							{
								required: true,
								message: '请选择收款人类型',
								trigger: 'change',
							},
						],
						event: {
							type: 'change',
							cb: row => {
								this.payeeUserId.selectList = [];
								row.payeeUserId = undefined;
								row.payeeUserName = undefined;
								row.paymentCardId = undefined;
								row.paymentAccount = undefined;
								row.bankLineNumber = undefined;
								this.setPayeeUserIdList(row);
								return;
							},
						},
					},
					{
						label: '选择收款人',
						type: 'select',
						prop: 'payeeUserId',
						selectList: this.payeeUserId.selectList ?? [],
						rules: [
							{
								required: true,
								message: '请选择收款人',
								trigger: 'change',
							},
						],
						showDictValue: false,
						prototype: this.payeeUserId.prototype,
						event: {
							type: 'change',
							cb: row => {
								// if (row.payeeType == '3') {
								// 	this.setInfo(row.payeeUserId);
								// } else {
								// 	let item = this.payeeUserId.selectList.find(
								// 		e => row.payeeUserId == e.value,
								// 	);
								// 	row.payeeUserName = item?.label;
								// 	// row.paymentCardId = item.accountNumber;
								// 	// row.paymentAccount = item.bankName;
								// 	this.$refs.form.form_clearValidate(
								// 		'payeeUserName',
								// 	);
								// }
								this.infoData.payeeUserName = undefined;
								this.infoData.paymentCardId = undefined;
								this.infoData.paymentAccount = undefined;
								this.dicts.paymentAccount = [];
								this.setInfo(row.payeeType, row.payeeUserId);
							},
						},
					},
					{
						label: '使用日期',
						type: 'datePicker',
						prop: 'payTime',
						clounmMinWidth: '200px',
						datePickerType: 'month',
						valueFormat: 'yyyy-MM',
						rules: [
							{
								required: true,
								message: '请选择使用日期',
								trigger: 'change',
							},
						],
					},

					{
						label: '合同类型',
						type: 'checkboxGroup',
						prop: 'contractType',
						showDictValue: false,
						checkboxGroupList: this.dicts.contractTypeList ?? [],
						rules: [
							{
								required: true,
								message: '请选择合同类型',
								trigger: 'change',
							},
						],
					},
					{
						label: '收款账户开户行名称',
						type: 'select',
						prop: 'paymentAccount',
						selectList: this.dicts.paymentAccount,
						selectValue: 'paymentAccount',
						rules: [
							{
								required: true,
								message: '请输入收款账户开户行名称',
								trigger: 'blur',
							},
						],
						prototype: {
							loading: this.paymentAccountLoading,
						},
						event: {
							type: 'change',
							cb: row => {
								let item = this.dicts.paymentAccount?.find(
									e => e.paymentAccount == row.paymentAccount,
								);

								this.infoData.payeeUserName = item?.accountName;
								this.infoData.paymentCardId = item?.cardNumber;
								this.infoData.bankLineNumber = item?.bankLineNumber;
							},
						},
					},
					{
						label: '收款人名称',
						type: 'input',
						state: 'readonly',
						prop: 'payeeUserName',
						rules: [
							{
								required: true,
								message: '请输入收款人名称',
								trigger: 'blur',
							},
						],
					},
					{
						label: '收款账号',
						type: 'input',
						state: 'readonly',
						prop: 'paymentCardId',
						rules: [
							{
								required: true,
								message: '请输入收款账号',
								trigger: 'blur',
							},
							{
								pattern: regs.BANK_ACC_REG,
								message: '请输入正确银行卡卡号',
								trigger: 'blur',
							},
						],
					},
					// {
					// 	label: '收款账户开户行名称',
					// 	type: 'input',
					// 	prop: 'paymentAccount',
					// 	rules: [
					// 		{
					// 			required: true,
					// 			message: '请输入收款账户开户行名称',
					// 			trigger: 'blur',
					// 		},
					// 	],
					// },
				];
			},
		},
		watch: {
			infoData: {
				handler(val) {
					this.formatValue();
				},
				deep: true,
				immediate: true,
			},
		},
		created() {},
		mounted() {
			let unWatch = this.$watch(
				'infoData.payeeType',
				val => {
					if (this.notEmpty(val)) {
						this.setPayeeUserIdList(this.infoData);
						this.setInfo(this.infoData.payeeType, this.infoData.payeeUserId, 'mounted');
						if (unWatch) {
							unWatch?.();
						}
					}
				},
				{
					deep: true,
					immediate: true,
				},
			);
			this.initDeptList();
		},

		methods: {
			async setPayeeUserIdList(row) {
				switch (row.payeeType) {
					case '1':
						// if (!this.infoData.companyId) {
						// 	this.$message({
						// 		message: '请先选择所属公司',
						// 		type: 'warning',
						// 	});
						// 	row.payeeType = '';
						// 	break;
						// }
						this.payeeUserId.selectList = [];
						this.payeeUserId.prototype.loading = true;
						await this.getUserList();
						break;
					case '2':
						this.payeeUserId.selectList = [];
						this.payeeUserId.prototype.loading = true;
						await this.getDriverList();
						break;
					case '3':
						this.payeeUserId.selectList = [];
						this.payeeUserId.prototype.loading = true;
						await this.getSupplierlist();
						break;
				}

				this.$forceUpdate();
				return;
			},
			setInfo(payType, supplierId, type) {
				console.log(payType, supplierId, type);

				if (this.Empty(payType) || this.Empty(supplierId)) {
					this.dicts.paymentAccount = [];
					this.infoData.payeeUserName = undefined;
					this.infoData.paymentCardId = undefined;
					this.infoData.paymentAccount = undefined;
					this.infoData.bankLineNumber = undefined;
					return;
				}
				let method = null,
					params = {};
				if (payType == 3) {
					method = SupplierDetails;
					params = supplierId;
				} else if (payType == 1) {
					method = clientDetails;
					params = { userId: supplierId, accountStatus: 0 };
				} else if (payType == 2) {
					method = DriverDetails;
					params = { driverId: supplierId, accountStatus: 0 };
				}
				this.paymentAccountLoading = true;
				method(params)
					.then(res => {
						if (res.code == 200) {
							let itemlist = [];
							if (payType == 1) {
								itemlist = res.data?.filter(item => {
									item.label = item.bankName;
									item.paymentAccount = item.bankName;
									item.cardNumber = item.accountNumber;
									item.bankLineNumber = item.bankCode;
									item.accountName = item.accountName;
									return item.accountStatus == '0';
								});
								this.dicts.paymentAccount = itemlist;
							}
							if (payType == 2) {
								itemlist = res.rows?.filter(item => {
									item.label = item.bankName;
									item.paymentAccount = item.bankName;
									item.cardNumber = item.accountNumber;
									item.bankLineNumber = item.bankCode;
									item.accountName = item.accountName;
									return item.accountStatus == '0';
								});
								this.dicts.paymentAccount = itemlist;
							}
							if (payType == 3) {
								itemlist = res.data?.accounts?.filter(item => {
									item.label = item.bankName;
									item.paymentAccount = item.bankName;
									item.cardNumber = item.accountNumber;
									item.bankLineNumber = item.bankCode;
									item.accountName = item.accountName;
									return item.accountStatus == '0';
								});
								this.dicts.paymentAccount = itemlist;
							}
							this.dicts.paymentAccount = itemlist;

							// 设置默认值
							if (type !== 'mounted') {
								this.infoData.payeeUserName = itemlist?.[0]?.accountName;
								this.infoData.paymentAccount = itemlist?.[0]?.paymentAccount;
								this.infoData.paymentCardId = itemlist?.[0]?.cardNumber;
								this.infoData.bankLineNumber = itemlist?.[0]?.bankLineNumber;
							}
						}
					})
					.finally(() => {
						this.paymentAccountLoading = false;
					});
			},
			initDeptList() {
				this.getDeptList(2);
			},
			getDeptList(deptType) {
				let params = {
					deptType,
				};
				apis.DeptList(params)
					.then(res => {
						if (res.code == 200) {
							switch (deptType) {
								case 1:
									this.deptList.department = res?.data ?? [];
									break;
								case 2:
									this.deptList.company = res?.data ?? [];
									break;
							}
						}
					})
					.finally(() => {});
			},
			getUserList() {
				return new Promise(resolve => {
					this.payeeUserId.prototype.loading = true;

					// let params = { deptId: this.infoData.companyId };
					let params = {};
					UserList(params)
						.then(res => {
							if (res.code == 200) {
								let arr = [];
								res.data.map(item => {
									arr.push({
										label: item.nickName,
										value: item.userId,
									});
								});
								this.payeeUserId.selectList = arr;
							} else {
								throw new Error(res);
							}
						})
						.catch(err => {
							console.log(err);
						})
						.finally(() => {
							resolve();
							this.payeeUserId.prototype.loading = false;
						});
				});
			},
			getDriverList() {
				return new Promise(resolve => {
					this.payeeUserId.prototype.loading = true;
					let comName = this.deptList?.company.find(
						item => item.deptId == this.infoData.companyId,
					);
					// let params = { belongCompanyName: comName?.deptName };
					let params = { approvalStatus: 2 };
					apis.DriverList(params)
						.then(res => {
							if (res.code == 200) {
								let arr = [];
								res.rows.map(item => {
									arr.push({
										label: item.driverName,
										value: item.driverId,
									});
								});
								this.payeeUserId.selectList = arr;
							} else {
								throw new Error(res);
							}
						})
						.catch(err => {
							console.log(err);
							// resolve([]);
						})
						.finally(() => {
							resolve();
							this.payeeUserId.prototype.loading = false;
						});
				});
			},
			getSupplierlist() {
				return new Promise(resolve => {
					this.payeeUserId.prototype.loading = true;

					apis.SupplierList({
						approvalStatus: 2,
					})
						.then(res => {
							if (res.code == 200) {
								let arr = [];
								res.rows.map(item => {
									arr.push({
										label: item.supplierName,
										value: item.supplierId,
									});
								});
								this.payeeUserId.selectList = arr;
							} else {
								throw new Error(res);
							}
						})
						.catch(() => {})
						.finally(() => {
							resolve();
							this.payeeUserId.prototype.loading = false;
						});
				});
			},
			valid() {
				return new Promise(async resolve => {
					let result = true;
					let refs = Object.values(this.$refs);
					for (let index = 0; index < refs?.length; index++) {
						const ref = refs[index];
						if (Object.prototype.toString.call(ref) == '[object Array]') {
							for (let i = 0; i < ref.length; i++) {
								const element = ref[i];
								if (element?.valid) {
									let rc = await element?.valid?.();
									result = result && rc;
								}
								if (element?.validate) {
									let rf = await this._valid(ref);
									result = result && rf;
								}
								if (element?.form_validate) {
									let rf = await this._valid(ref, 'form_validate');
									result = result && rf;
								}
							}
						} else {
							if (ref?.valid) {
								let rc = await ref?.valid?.();
								result = result && rc;
							}
							if (ref?.validate) {
								let rf = await this._valid(ref);
								result = result && rf;
							}
							if (ref?.form_validate) {
								let rf = await this._valid(ref, 'form_validate');
								result = result && rf;
							}
						}
					}

					resolve(result);
				});
			},
			formatValue() {
				if (
					this.notEmpty(this.infoData?.contractType) &&
					typeof this.infoData?.contractType == 'string'
				) {
					let contractType = this.infoData?.contractType?.split?.(',') ?? [];
					this.$set(this.infoData, 'contractType', contractType);
				}
				if (!Array.isArray(this.infoData.contractType)) {
					this.$set(this.infoData, 'contractType', []);
				}
			},
		},
	};
</script>
<style lang="scss" scoped>
	.container {
		border-radius: 10px;
		background-color: #fff;
		// margin: 20px;
		padding: 20px;
		.container_title {
			margin-bottom: 30px;
			border-bottom: 1px solid #e9e9e9;
			font-weight: 600;
			display: flex;
			justify-content: space-between;
			padding-bottom: 15px;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			font-size: 16px;
			color: #333333;
			line-height: 22px;
			text-align: left;
			font-style: normal;
		}
		.container_content {
			// padding: 20px;
		}
	}
</style>
